import com.google.gson.Gson
import com.ug_project.dict.engine.DictEngine
import com.ug_project.dict.engine.entity.DictItem
import java.io.File
import java.nio.channels.FileChannel
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.StandardOpenOption

/**
Company: Sarkar software technologys
WebSite: http://www.sarkar.cn
Author: yeganaaa
Date : 8/1/18
Time: 1:02 AM
 */
data class Segment(val items: Array<DictItem>)

fun provideDictEngine(autoClean: Boolean = true, action: (DictEngine) -> Unit) {
    val wordTableFile = Paths.get("temp_wordtable.wdt")
    val indexTableFile = Paths.get("temp_indextable.ipt")
    val dataTableFile = Paths.get("temp_datatable.ddt")

    if (autoClean) {
        Files.deleteIfExists(wordTableFile)
        Files.deleteIfExists(indexTableFile)
        Files.deleteIfExists(dataTableFile)
    }

    if (Files.notExists(wordTableFile)) Files.createFile(wordTableFile)
    if (Files.notExists(indexTableFile)) Files.createFile(indexTableFile)
    if (Files.notExists(dataTableFile)) Files.createFile(dataTableFile)

    val wordTableChannel = FileChannel.open(wordTableFile, StandardOpenOption.READ, StandardOpenOption.WRITE)
    val indexTableChannel = FileChannel.open(indexTableFile, StandardOpenOption.READ, StandardOpenOption.WRITE)
    val dataTableChannel = FileChannel.open(dataTableFile, StandardOpenOption.READ, StandardOpenOption.WRITE)

    val engine = DictEngine(wordTableChannel, indexTableChannel, dataTableChannel)
    action(engine)

    wordTableChannel.close()
    indexTableChannel.close()
    dataTableChannel.close()


}

fun main(args: Array<String>) {
    provideDictEngine { engine ->
        val items = Gson().fromJson(File("json/enuy.json").readText(), Array<Segment>::class.java)
        items.forEachIndexed { index, segment ->
            segment.items.forEach {
                engine.addNewWord(it)
            }
            println(index * 33)
        }
        println("okay")
    }
}